/*
 * @Descripttion:
 * @version:
 * @Author: qiaobangzhu
 * @Date: 2019-07-04 01:36:52
 * @LastEditors: qiaobangzhu
 * @LastEditTime: 2020-11-28 15:32:49
 */
import Cookies from 'js-cookie'

const TokenKey = '_b2zg_jxc'

function isIP (ip) {
  var re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/// 正则表达式
  if (re.test(ip)) {
    if (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256) { return true }
  }
  return false
}

/**
 * 获取跟域名
 * @returns
 */
function getMainHost () {
  const key = `mh_${Math.random()}`
  const keyR = new RegExp(`(^|;)\\s*${key}=12345`)
  const expiredTime = new Date(0)
  const domain = document.domain
  const domainList = domain.split('.')

  const urlItems = []
  // 主域名一定会有两部分组成
  urlItems.unshift(domainList.pop())
  // 慢慢从后往前测试
  while (domainList.length) {
    urlItems.unshift(domainList.pop())
    const mainHost = urlItems.join('.')
    const cookie = `${key}=${12345};domain=.${mainHost}`

    document.cookie = cookie

    // 如果cookie存在，则说明域名合法
    if (keyR.test(document.cookie)) {
      document.cookie = `${cookie};expires=${expiredTime}`
      return mainHost
    }
  }
}

/**
 * 获取父级域名
 * @returns
 */
const getDomain = function () {
  const url = document.domain
  if (isIP(url)) {
    return null
  }
  return getMainHost()
}

export function getToken () {
  return Cookies.get(TokenKey) || ''
}

export function setToken (token) {
  if (token) {
    const domain = getDomain()
    if (domain) {
      Cookies.set(TokenKey, token, { domain })
    } else {
      Cookies.set(TokenKey, token)
    }
  }
}

export function removeToken () {
  const domain = getDomain()
  if (domain) {
    return Cookies.remove(TokenKey, { domain })
  }
  return Cookies.remove(TokenKey)
}
